﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SubSonic;
using Newtonsoft.Json.Linq;
using ExtAspNet;


namespace TCMSystem
{
    public partial class main : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Page_Init

        protected void Page_Init(object sender, EventArgs e)
        {
            // 工具栏上的帮助菜单
            //Nii.JSON.JSONArray ja = new Nii.JSON.JSONArray(TblMstConfigHelper.HelpList);
            JArray ja = JArray.Parse(TblMstConfigHelper.HelpList);
            foreach (JObject jo in ja)
            {
                MenuButton menuItem = new MenuButton();
                menuItem.EnablePostBack = false;
                menuItem.Text = jo.Value<string>("Text");
                //menuItem.Icon = (Icon)StringUtil.EnumFromName(typeof(Icon), jo.Value<string>("Icon"));
                menuItem.Icon = IconHelper.String2Icon(jo.Value<string>("Icon"), true);
                menuItem.OnClientClick = String.Format("addExampleTab('{0}', '{1}', '{2}')", jo.Value<string>("ID"), ResolveUrl(jo.Value<string>("URL")), jo.Value<string>("Text"));

                btnHelp.Menu.Items.Add(menuItem);
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitMenu();
                LoadData();
            }
        }

        private void LoadData()
        {
            //txtUser.Text = String.Format("欢迎您：<span style=\"font-weight:bold;color:red;\">{0}</span> [{1}]", User.Identity.Name, Request.UserHostAddress);
            //txtOnlineUserCount.Text = String.Format("在线用户：{0}", "2");

            //btnSysConfig.OnClientClick = Window1.GetShowReference("~/admin/config.aspx", "系统设置");

        }


        #endregion

        #region InitMenu

        private void InitMenu()
        {
            //TblMstMenuCollection menus = new Select().From<TblMstMenu>()
            //    //.Where(TblMstMenu.IsMainMenuColumn).IsEqualTo(true)
            //    .OrderAsc(TblMstMenu.SortIndexColumn.ColumnName)
            //    .ExecuteAsCollection<TblMstMenuCollection>();

            List<CustomMenu> menus = new List<CustomMenu>();
            List<CustomMenu> originalMenus = CustomMenuHelper.GetCustomMenus();

            // 当前角色可以显示的菜单列表
            List<int> menuIds = RoleMenuHelper.GetRoleMenus(GetIdentityRoleId());
            foreach (CustomMenu menu in originalMenus)
            {
                if (menuIds.Contains(menu.Id))
                {
                    menus.Add(menu);
                }
            }

            // 生成树
            ResolveMenuTree(menus, 0, treeMenu.Nodes);

            if (treeMenu.Nodes.Count == 0)
            {
                Response.Write("系统管理员尚未给你配置菜单！");
                Response.End();

                return;
            }
            
            // 展开第一个树节点
            treeMenu.Nodes[0].Expanded = true;

            #region old code
            //if (TblMstConfigHelper.MenuType.ToLower() == "accordion")
            //{
            //    Accordion accordion = new Accordion();
            //    regionLeft.Items.Add(accordion);
            //    accordion.ShowBorder = false;
            //    accordion.ShowHeader = false;

            //    foreach (MyMenu menu in newMenus)
            //    {
            //        if (menu.ParentMenuId == 0)
            //        {
            //            AccordionPane pane = new AccordionPane();
            //            accordion.Panes.Add(pane);
            //            pane.Title = menu.Name;
            //            pane.ShowBorder = false;

            //            Tree tree = new Tree();
            //            pane.Items.Add(tree);
            //            tree.ShowBorder = false;
            //            tree.ShowHeader = false;
            //            tree.AutoScroll = true;
            //            tree.EnableArrows = true;

            //            ResolveMenuTree(newMenus, menu.Id, tree.Nodes);
            //        }
            //    }
            //}
            //else
            //{
            //    Tree tree = new Tree();
            //    regionLeft.Items.Add(tree);
            //    tree.ShowBorder = false;
            //    tree.ShowHeader = false;
            //    tree.AutoScroll = true;
            //    tree.EnableArrows = true;

            //    ResolveMenuTree(newMenus, 0, tree.Nodes);
            //} 
            #endregion
        }


        /// <summary>
        /// 生成菜单树
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="parentMenuId"></param>
        /// <param name="nodes"></param>
        private void ResolveMenuTree(List<CustomMenu> menus, int parentMenuId, ExtAspNet.TreeNodeCollection nodes)
        {
            foreach (CustomMenu menu in menus)
            {
                if (menu.ParentId == parentMenuId)
                {
                    ExtAspNet.TreeNode node = new ExtAspNet.TreeNode();
                    nodes.Add(node);

                    node.Text = menu.Title;
                    node.IconUrl = menu.ImageUrl;
                    if (!String.IsNullOrEmpty(menu.NavigateUrl))
                    {
                        node.EnablePostBack = false;
                        node.NavigateUrl = ResolveUrl(menu.NavigateUrl);
                        //node.OnClientClick = String.Format("addTab('{0}','{1}','{2}')", node.NodeID, ResolveUrl(menu.NavigateUrl), node.Text.Replace("'", ""));
                    }
                    if (menu.IsTreeLeaf)
                    {
                        node.Leaf = true;
                    }

                    ResolveMenuTree(menus, menu.Id, node.Nodes);
                }
            }
        }

        #endregion

        #region Events

        protected void btnExit_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
        }

        #endregion
    }
}
